{% extends "base.html" %}

{% block title %}设置 - 漫画阅读器{% endblock %}

{% block content %}
<div class="settings-container">
    <!-- 页面标题 -->
    <section class="settings-header">
        <h1 class="page-title">系统设置</h1>
        <p class="page-subtitle">管理您的漫画阅读器配置</p>
    </section>

    <!-- 系统统计 -->
    <section class="stats-section">
        <div class="section-header">
            <h2 class="section-title">系统统计</h2>
        </div>
        
        <div class="stats-cards">
            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-icon">📚</span>
                    <span class="stat-title">漫画库</span>
                </div>
                <div class="stat-content">
                    <div class="stat-row">
                        <span class="stat-label">漫画数量:</span>
                        <span class="stat-value">{{ library_stats.total_comics or 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">章节数量:</span>
                        <span class="stat-value">{{ library_stats.total_chapters or 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">总页数:</span>
                        <span class="stat-value">{{ library_stats.total_pages or 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">扫描路径:</span>
                        <span class="stat-value">{{ library_stats.comic_path or '未设置' }}</span>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-icon">💾</span>
                    <span class="stat-title">缓存状态</span>
                </div>
                <div class="stat-content">
                    <div class="stat-row">
                        <span class="stat-label">缓存文件:</span>
                        <span class="stat-value">{{ cache_stats.total_files or 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">缓存大小:</span>
                        <span class="stat-value">{{ cache_stats.total_size_str or '0B' }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">使用率:</span>
                        <span class="stat-value">{{ "%.1f"|format(cache_stats.usage_percentage or 0) }}%</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">过期文件:</span>
                        <span class="stat-value">{{ cache_stats.expired_count or 0 }}</span>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-icon">🖼️</span>
                    <span class="stat-title">图片缓存</span>
                </div>
                <div class="stat-content">
                    <div class="stat-row">
                        <span class="stat-label">处理后图片:</span>
                        <span class="stat-value">{{ image_cache_stats.images.count or 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">缩略图:</span>
                        <span class="stat-value">{{ image_cache_stats.thumbnails.count or 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">总大小:</span>
                        <span class="stat-value">
                            {% set total_size = (image_cache_stats.images.size or 0) + (image_cache_stats.thumbnails.size or 0) %}
                            {% if total_size > 1073741824 %}
                                {{ "%.1f"|format(total_size / 1073741824) }}GB
                            {% elif total_size > 1048576 %}
                                {{ "%.1f"|format(total_size / 1048576) }}MB
                            {% elif total_size > 1024 %}
                                {{ "%.1f"|format(total_size / 1024) }}KB
                            {% else %}
                                {{ total_size }}B
                            {% endif %}
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 缓存管理 -->
    <section class="cache-section">
        <div class="section-header">
            <h2 class="section-title">缓存管理</h2>
        </div>
        
        <div class="cache-actions">
            <div class="action-card">
                <div class="card-content">
                    <div class="card-icon">🧹</div>
                    <div class="card-info">
                        <h3 class="card-title">清理过期缓存</h3>
                        <p class="card-desc">删除已过期的缓存文件，释放存储空间</p>
                    </div>
                </div>
                <button class="card-btn" onclick="clearCache('expired')">清理</button>
            </div>
            
            <div class="action-card">
                <div class="card-content">
                    <div class="card-icon">🗑️</div>
                    <div class="card-info">
                        <h3 class="card-title">清空所有缓存</h3>
                        <p class="card-desc">删除所有缓存文件，包括图片和系统缓存</p>
                    </div>
                </div>
                <button class="card-btn danger" onclick="clearCache('all')">清空</button>
            </div>
            
            <div class="action-card">
                <div class="card-content">
                    <div class="card-icon">🖼️</div>
                    <div class="card-info">
                        <h3 class="card-title">清理图片缓存</h3>
                        <p class="card-desc">只删除处理后的图片和缩略图缓存</p>
                    </div>
                </div>
                <button class="card-btn" onclick="clearCache('images')">清理</button>
            </div>
        </div>
    </section>

    <!-- 系统操作 -->
    <section class="system-section">
        <div class="section-header">
            <h2 class="section-title">系统操作</h2>
        </div>
        
        <div class="system-actions">
            <div class="action-card">
                <div class="card-content">
                    <div class="card-icon">🔄</div>
                    <div class="card-info">
                        <h3 class="card-title">重新扫描漫画</h3>
                        <p class="card-desc">强制重新扫描漫画目录，更新漫画库</p>
                    </div>
                </div>
                <button class="card-btn" onclick="scanComics(true)">扫描</button>
            </div>
            
            <div class="action-card">
                <div class="card-content">
                    <div class="card-icon">📊</div>
                    <div class="card-info">
                        <h3 class="card-title">系统信息</h3>
                        <p class="card-desc">查看详细的系统运行状态和统计信息</p>
                    </div>
                </div>
                <button class="card-btn" onclick="showSystemInfo()">查看</button>
            </div>
            
            <div class="action-card">
                <div class="card-content">
                    <div class="card-icon">📥</div>
                    <div class="card-info">
                        <h3 class="card-title">导出配置</h3>
                        <p class="card-desc">导出当前系统配置和漫画库信息</p>
                    </div>
                </div>
                <button class="card-btn" onclick="exportConfig()">导出</button>
            </div>
        </div>
    </section>

    <!-- 阅读设置 -->
    <section class="reading-section">
        <div class="section-header">
            <h2 class="section-title">阅读设置</h2>
        </div>
        
        <div class="settings-form">
            <div class="setting-group">
                <div class="setting-item">
                    <label class="setting-label">默认图片质量</label>
                    <select class="setting-select" id="default-quality">
                        <option value="60">低质量 (60%)</option>
                        <option value="85" selected>标准质量 (85%)</option>
                        <option value="95">高质量 (95%)</option>
                        <option value="100">原始质量 (100%)</option>
                    </select>
                    <p class="setting-desc">调整图片压缩质量，影响加载速度和文件大小</p>
                </div>
                
                <div class="setting-item">
                    <label class="setting-label">预加载页面数</label>
                    <input type="number" class="setting-input" id="preload-pages" min="0" max="10" value="2">
                    <p class="setting-desc">设置提前加载的页面数量，提高阅读流畅度</p>
                </div>
                
                <div class="setting-item">
                    <label class="setting-label">触摸灵敏度</label>
                    <input type="range" class="setting-range" id="touch-sensitivity" min="30" max="100" value="50">
                    <p class="setting-desc">调整手势操作的灵敏度</p>
                </div>
            </div>
            
            <div class="setting-group">
                <div class="setting-item checkbox-item">
                    <input type="checkbox" class="setting-checkbox" id="auto-hide-controls" checked>
                    <label class="checkbox-label" for="auto-hide-controls">自动隐藏控制栏</label>
                    <p class="setting-desc">阅读时自动隐藏顶部和底部控制栏</p>
                </div>
                
                <div class="setting-item checkbox-item">
                    <input type="checkbox" class="setting-checkbox" id="enable-preload" checked>
                    <label class="checkbox-label" for="enable-preload">启用预加载</label>
                    <p class="setting-desc">自动预加载相邻页面，提高阅读体验</p>
                </div>
                
                <div class="setting-item checkbox-item">
                    <input type="checkbox" class="setting-checkbox" id="save-progress" checked>
                    <label class="checkbox-label" for="save-progress">保存阅读进度</label>
                    <p class="setting-desc">自动记住每部漫画的阅读位置</p>
                </div>
            </div>
            
            <div class="settings-actions">
                <button class="action-btn primary" onclick="saveSettings()">保存设置</button>
                <button class="action-btn secondary" onclick="resetSettings()">恢复默认</button>
            </div>
        </div>
    </section>
</div>

<!-- 系统信息弹窗 -->
<div class="modal" id="system-info-modal">
    <div class="modal-overlay" onclick="closeModal()"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">系统信息</h3>
            <button class="modal-close" onclick="closeModal()">×</button>
        </div>
        <div class="modal-body" id="system-info-content">
            <!-- 系统信息内容将通过JavaScript动态加载 -->
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 加载用户设置
    loadUserSettings();
});

// 清理缓存
function clearCache(type) {
    let message, endpoint;
    
    switch(type) {
        case 'expired':
            message = '确定要清理过期缓存吗？';
            endpoint = '/api/cache/clear?type=expired';
            break;
        case 'all':
            message = '确定要清空所有缓存吗？这将删除所有缓存文件。';
            endpoint = '/api/cache/clear?type=all';
            break;
        case 'images':
            message = '确定要清理图片缓存吗？';
            endpoint = '/api/cache/clear?type=images';
            break;
        default:
            return;
    }
    
    if (confirm(message)) {
        showLoading('正在清理缓存...');
        
        fetch(endpoint, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert('缓存清理完成！');
                location.reload();
            } else {
                throw new Error(data.message);
            }
        })
        .catch(error => {
            console.error('清理缓存失败:', error);
            alert('清理失败，请稍后重试');
        })
        .finally(() => {
            hideLoading();
        });
    }
}

// 扫描漫画
function scanComics(force = false) {
    const message = force ? '确定要强制重新扫描漫画目录吗？' : '确定要扫描漫画目录吗？';
    
    if (confirm(message)) {
        showLoading('正在扫描漫画目录...');
        
        fetch(`/api/scan?force=${force}`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                const stats = data.data;
                alert(`扫描完成！找到 ${stats.total_comics} 部漫画，${stats.total_chapters} 个章节，${stats.total_pages} 页`);
                location.reload();
            } else {
                throw new Error(data.message);
            }
        })
        .catch(error => {
            console.error('扫描失败:', error);
            alert('扫描失败，请稍后重试');
        })
        .finally(() => {
            hideLoading();
        });
    }
}

// 显示系统信息
function showSystemInfo() {
    showLoading('正在获取系统信息...');
    
    fetch('/api/stats')
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                displaySystemInfo(data.data);
                document.getElementById('system-info-modal').classList.add('active');
            } else {
                throw new Error(data.message);
            }
        })
        .catch(error => {
            console.error('获取系统信息失败:', error);
            alert('获取系统信息失败');
        })
        .finally(() => {
            hideLoading();
        });
}

// 显示系统信息内容
function displaySystemInfo(data) {
    const content = document.getElementById('system-info-content');
    content.innerHTML = `
        <div class="info-section">
            <h4>漫画库信息</h4>
            <div class="info-grid">
                <div class="info-item">
                    <span class="info-label">漫画数量:</span>
                    <span class="info-value">${data.library.total_comics}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">章节数量:</span>
                    <span class="info-value">${data.library.total_chapters}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">总页数:</span>
                    <span class="info-value">${data.library.total_pages}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">扫描路径:</span>
                    <span class="info-value">${data.library.comic_path}</span>
                </div>
            </div>
        </div>
        
        <div class="info-section">
            <h4>缓存信息</h4>
            <div class="info-grid">
                <div class="info-item">
                    <span class="info-label">缓存文件数:</span>
                    <span class="info-value">${data.cache.total_files}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">缓存大小:</span>
                    <span class="info-value">${data.cache.total_size_str}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">使用率:</span>
                    <span class="info-value">${data.cache.usage_percentage.toFixed(1)}%</span>
                </div>
                <div class="info-item">
                    <span class="info-label">最大缓存:</span>
                    <span class="info-value">${data.cache.max_cache_size_str}</span>
                </div>
            </div>
        </div>
        
        <div class="info-section">
            <h4>图片缓存信息</h4>
            <div class="info-grid">
                <div class="info-item">
                    <span class="info-label">处理后图片:</span>
                    <span class="info-value">${data.image_cache.images.count}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">缩略图:</span>
                    <span class="info-value">${data.image_cache.thumbnails.count}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">总文件数:</span>
                    <span class="info-value">${data.image_cache.total_files}</span>
                </div>
            </div>
        </div>
    `;
}

// 关闭弹窗
function closeModal() {
    document.getElementById('system-info-modal').classList.remove('active');
}

// 导出配置
function exportConfig() {
    const config = {
        library_stats: {{ library_stats | tojson | safe }},
        cache_stats: {{ cache_stats | tojson | safe }},
        image_cache_stats: {{ image_cache_stats | tojson | safe }},
        user_settings: getUserSettings(),
        export_time: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `comic-reader-config-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    alert('配置文件已导出！');
}

// 保存设置
function saveSettings() {
    const settings = {
        defaultQuality: document.getElementById('default-quality').value,
        preloadPages: document.getElementById('preload-pages').value,
        touchSensitivity: document.getElementById('touch-sensitivity').value,
        autoHideControls: document.getElementById('auto-hide-controls').checked,
        enablePreload: document.getElementById('enable-preload').checked,
        saveProgress: document.getElementById('save-progress').checked
    };
    
    localStorage.setItem('comic_reader_settings', JSON.stringify(settings));
    alert('设置已保存！');
}

// 重置设置
function resetSettings() {
    if (confirm('确定要恢复默认设置吗？')) {
        localStorage.removeItem('comic_reader_settings');
        loadUserSettings();
        alert('设置已重置为默认值！');
    }
}

// 加载用户设置
function loadUserSettings() {
    const defaultSettings = {
        defaultQuality: '85',
        preloadPages: '2',
        touchSensitivity: '50',
        autoHideControls: true,
        enablePreload: true,
        saveProgress: true
    };
    
    try {
        const saved = localStorage.getItem('comic_reader_settings');
        const settings = saved ? { ...defaultSettings, ...JSON.parse(saved) } : defaultSettings;
        
        document.getElementById('default-quality').value = settings.defaultQuality;
        document.getElementById('preload-pages').value = settings.preloadPages;
        document.getElementById('touch-sensitivity').value = settings.touchSensitivity;
        document.getElementById('auto-hide-controls').checked = settings.autoHideControls;
        document.getElementById('enable-preload').checked = settings.enablePreload;
        document.getElementById('save-progress').checked = settings.saveProgress;
    } catch (e) {
        console.error('加载用户设置失败:', e);
    }
}

// 获取用户设置
function getUserSettings() {
    try {
        const saved = localStorage.getItem('comic_reader_settings');
        return saved ? JSON.parse(saved) : {};
    } catch (e) {
        return {};
    }
}
</script>
{% endblock %}